<?php
/**
 * Created by PhpStorm.
 * User: HP
 * Date: 2018/9/11
 * Time: 16:24
 */
namespace App\Http\Controllers;

use App\Models\BorrowRecord;
use App\Models\Fine;
use App\Models\ReturnRecord;
use function foo\func;
use Illuminate\Database\QueryException;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Auth;
use App\Models\Book;
use App\Models\InventoryRecord;
use Illuminate\Support\Facades\Validator;
use Tymon\JWTAuth\Facades\JWTAuth;

class BooksController extends Controller {

    public function addBooks(Request $request){
        $cname = $request->input('cname');
        $cid = DB::table('categories')->where('name',$cname)->select('cid')->first();
        if($cid == null){
            return $this->fail(500002,'图书类别不存在');
        }
        $cid = $cid->cid;
        $result = Book::addBooks($request, $cid);


        if(isset($result)){

            $admin_id = Auth::id();
            $bid = $result->bid;
            $total_num = $result->total_num;
            $inventory = InventoryRecord::purchaseBook($admin_id,$bid,$total_num);
            if(isset($inventory)){
                return $this->success($bid);
            }
            else{
                return $this->fail(500001,'inventories_table error');
            }
        }else{
            return $this->fail(500001,'books_table error');
        }
    }

    public function bookList(){
//        $result = Book::getList();
//        $cid = DB::table('books')->where('bid',$bid)->select('cid')->first()->cid;
        $result = DB::table('books')->where('total_num','>',0)->join('categories','books.cid','=','categories.cid')->select(
            'bid','books.name','categories.name as cname','author','publisher','total_num',
            'remain_num','price','books.created_at','books.updated_at'
        )->get()->toArray();
        if($result != null){
            return $this->success($result);
        }else{
            return $this->fail(500002,'目录不存在或服务器未响应');
        }
    }

    public function deleteBooks(Request $request){
        $result = Book::deleteBooks($request);
        $bid = $request->input('bid');
        $number = $request->input('number');
        if($result){
            $admin_uid = Auth::id();
            $delete = InventoryRecord::deleteBooks($admin_uid,$bid,$number);
            if(isset($delete)){
                return $this->success('删除成功');
            }else{
                return $this->fail(500001,'inventories_table error');
            }
        }else{
            return $this->fail(500001,'现存数量少于要删除数量');
        }
    }

    public function increaseBooks(Request $request){
        $result = Book::increaseBooks($request);
        $bid = $request->input('bid');
        $number = $request->input('number');
        if($result){
            $admin_uid = Auth::id();
            $increase = InventoryRecord::purchaseBook($admin_uid,$bid,$number);
            if(isset($increase)){
                return $this->success('增加成功');
            }else{
                return $this->fail(500001,'inventories_table error');
            }
        }else{
            return $this->fail(500001);
        }
    }

    public function searchBooks(Request $request){
        $books = DB::table('books')->where('total_num','>',0);
        $name = $request->input('name');
        $author = $request->input('author');
        $publisher = $request->input('publisher');
        if(isset($name)){
            $books->where('name','like','%'.$name.'%');
        }

        if(isset($author)){
            $books->where('author','like','%'.$author.'%');
        }
        if(isset($publisher)){
            $books->where('publisher','like','%'.$publisher.'%');
        }
        $books = $books->get();

        if(isset($books)){
            return $this->success($books);
        }else{
            return $this->fail(500002);
        }
    }

    public function increaseList(){
        $result = DB::table('inventory_records')->where('operation',1)
            ->join('users','inventory_records.admin_uid','=','users.id')
            ->join('books','inventory_records.bid','=','books.bid')
            ->select('inventory_records.bid','books.name as bname','inventory_records.admin_uid','users.username',
                'inventory_records.number','inventory_records.created_at','inventory_records.updated_at'
        )->get()->toArray();
        if($result != null){
            return $this->success($result);
        }else{
            return $this->fail(500002,'未找到增加记录');
        }

    }

    public function deleteList()
    {
        $result = DB::table('inventory_records')->where('operation', 0)
            ->join('users', 'inventory_records.admin_uid', '=', 'users.id')
            ->join('books', 'inventory_records.bid', '=', 'books.bid')
            ->select('inventory_records.bid', 'books.name as bname', 'inventory_records.admin_uid', 'users.username',
                'inventory_records.number', 'inventory_records.created_at', 'inventory_records.updated_at'
            )->get()->toArray();
        if ($result != null) {
            return $this->success($result);
        } else {
            return $this->fail(500002, '未找到删除记录');
        }
    }

    public function borrowBooks(Request $request)
    {
      $validate=Validator::make($request->all(),[
            'bid'=>'required|exists:books,bid',
        ]);

        $bid=$request->get('bid');

        $remain=false;
        $name="";

            $book=Book::where('bid',$bid)->get()[0];
            $remain_num=$book->remain_num;
            if($remain_num==0)
            {
                $remain=true;
                $name=$book->name;
            }


        if($validate->fails()||$remain)
        {
            $error=$validate->errors();
            if($remain)
            {
                $error->add('remain_num',$name .'库存不足！');
            }
            return $this->fail(400006,$error);
        }
        $user=JWTAuth::parseToken()->authenticate();
        $has_borrowed_number=BorrowRecord::where('uid',$user->id)->where('state','<',2)->count();

        if($user->state>=1||$has_borrowed_number>=$user->borrow_num)
        {
            return $this->fail(400007);
        }
        DB::beginTransaction();

            try
            {
                BorrowRecord::create([
                    'uid'=>$user->id,
                    'bid'=>$bid,
                    'state'=>0,
                    'timescale'=>date('Y-m-d H:i:s',strtotime('+1month'))
                ]);
                Book::where('bid',$bid)
                    ->decrement('remain_num',1);
            }
            catch (QueryException $e)
            {
                DB::rollback();
                return $this->fail(500003);
            }
        DB::commit();

        return $this->success();

    }

    public function returnBooks(Request $request)
    {
        $validate=Validator::make($request->all(),[
            'borrow_id'=>'array|required|exists:borrow_records,borrow_id',
        ]);
        $borrow_id=$request->get('borrow_id');

        $over_time=false;
        foreach ($borrow_id as $b)
        {
            $borrow_record=BorrowRecord::where('borrow_id',$b)->get()[0];
            $borrow_state=$borrow_record->state;
            if($borrow_state>=2)
            {
                $over_time=true;
            }
        }

        if($validate->fails()||$over_time)
        {
            $error=$validate->errors();
            if($over_time>=2){
                $error->add('state','状态错误！');
            }
            return $this->fail(400006,$error);
        }

        $user=JWTAuth::parseToken()->authenticate();
        $fine_book=0;
        DB::beginTransaction();
        foreach ($borrow_id as $b)
        {

            $borrow_record=BorrowRecord::where('borrow_id',$b)->get()[0];
            $borrow_state=$borrow_record->state;
            $is_paid=0;
            if($borrow_state==1)
            {
                $price=Fine::leftJoin('borrow_records as b','b.borrow_id','fines.borrow_id')
                    ->where('b.borrow_id',$b)
                    ->get()[0]
                    ->price;
                $is_paid=Fine::leftJoin('borrow_records as b','b.borrow_id','fines.borrow_id')
                    ->where('b.borrow_id',$b)
                    ->get()[0]
                    ->is_paid;

                if($is_paid==0)
                {
                    $fine_book+=$price;
                }
            }

                try
                {
                    BorrowRecord::where('borrow_id',$b)
                        ->update([
                            'state'=>$borrow_state==0?3:2,
                        ]);
                    ReturnRecord::create([
                        'borrow_id'=>$b,
                        'admin_uid'=>$user->id,
                    ]);
                    Book::where('bid',$borrow_record->bid)->increment('remain_num',1);
                    if($is_paid==0)
                    {
                        Fine::where('borrow_id',$b)->update([
                            'is_paid'=>1,
                             'paid_time'=>date('Y-m-d H:i:s')
                        ]);
                    }
                }
                catch (QueryException $e)
                {
                    DB::rollback();
                    return $this->fail(500003);
                }

        }

        DB::commit();
        if($fine_book!=0)
        {
            return $this->fail(400008,$fine_book);
        }

        return $this->success();

    }
}